/*
 * author GTVT
 */

import java.net.*;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.Arrays;

class UDPCC {

    static int portS = 2812;
    static String ipS = "127.0.0.1";

    public ArrayList ketNoi(String st) throws Exception {
        // Tao goi DatagramSocket
        DatagramSocket socket = new DatagramSocket();
        DatagramPacket packet;
        byte[] data;
        InetAddress addS = InetAddress.getByName(ipS);
        //chuyen du lieu sang mang byte
        data = st.getBytes("UTF8");
        // goi packet den may chu;
        packet = new DatagramPacket(data, data.length, addS, portS);
        socket.send(packet);
        // nhan packet tu may chu ;
        data = new byte[1024];
        packet = new DatagramPacket(data, data.length);
        //  System.out.println("Nhan Du Lieu");
        socket.setSoTimeout(1000);
        try {
            socket.receive(packet);
        } catch (SocketTimeoutException ex) {
            //   System.out.println("Recieve Time Out");
        }

        socket.close();

        //Doi mang bytes nhan duoc sang chuoi dinh danh Unicode
        //Dam bao chuong trinh chay tot khi duoc bien dich thanh jar(important)
        byte[] utf8bytes = Arrays.copyOf(packet.getData(), packet.getLength());
        String newkq = new String(utf8bytes, "UTF8");

        return Split(newkq, '+');

    }

    private static ArrayList Split(String s, char c) {
        int tam = 0;
        ArrayList a = new ArrayList();
        for (int i = 0; i < s.length(); ++i) {
            if (s.charAt(i) == '+') {
                a.add(s.substring(tam, i));
                tam = i + 1;
            }
        }
        return a;
    }
}
